package com.ruoyi.studentHelp.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import ch.qos.logback.classic.pattern.DateConverter;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.weChatRobot.template.QicqMailTemplate;
import com.ruoyi.common.weChatRobot.utils.WechatRobotUtil;
import com.ruoyi.studentHelp.AceUtil.LongEncryptionDemo;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.studentHelp.mapper.SysStudentHelpMapper;
import com.ruoyi.studentHelp.domain.SysStudentHelp;
import com.ruoyi.studentHelp.service.ISysStudentHelpService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 就业帮扶Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-23
 */
@Service
public class SysStudentHelpServiceImpl implements ISysStudentHelpService {
    @Autowired
    private SysStudentHelpMapper sysStudentHelpMapper;
    @Autowired
    private QicqMailTemplate qicqMailTemplate;


    /**
     * 查询就业帮扶
     *
     * @param id 就业帮扶主键
     * @return 就业帮扶
     */
    @Override
    public SysStudentHelp selectSysStudentHelpById(Long id) {
        return sysStudentHelpMapper.selectSysStudentHelpById(id);
    }

    /**
     * 查询就业帮扶列表
     *
     * @param sysStudentHelp 就业帮扶
     * @return 就业帮扶
     */
    @Override
    public List<SysStudentHelp> selectSysStudentHelpList(SysStudentHelp sysStudentHelp) {
        return sysStudentHelpMapper.selectSysStudentHelpList(sysStudentHelp);
    }

    /**
     * 新增就业帮扶
     *
     * @param sysStudentHelp 就业帮扶
     * @return 结果
     */
    @Override
    public int insertSysStudentHelp(SysStudentHelp sysStudentHelp) {
        return sysStudentHelpMapper.insertSysStudentHelp(sysStudentHelp);
    }

    /**
     * 修改就业帮扶
     *
     * @param sysStudentHelp 就业帮扶
     * @return 结果
     */
    @Override
    public int updateSysStudentHelp(SysStudentHelp sysStudentHelp) {
        return sysStudentHelpMapper.updateSysStudentHelp(sysStudentHelp);
    }

    /**
     * 批量删除就业帮扶
     *
     * @param ids 需要删除的就业帮扶主键
     * @return 结果
     */
    @Override
    public int deleteSysStudentHelpByIds(Long[] ids) {
        return sysStudentHelpMapper.deleteSysStudentHelpByIds(ids);
    }

    /**
     * 删除就业帮扶信息
     *
     * @param id 就业帮扶主键
     * @return 结果
     */
    @Override
    public int deleteSysStudentHelpById(Long id) {
        return sysStudentHelpMapper.deleteSysStudentHelpById(id);
    }

    /**
     * 文件上传到cos
     * @param file
     * @return
     */
    @Override
    public PutObjectResult uploadCos(MultipartFile file) throws IOException {
        //创建客户端
        // SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
        String secretId = "AKIDEQVWK6zognjdyJnFIUbh3HPKPTVSJ7uq";//用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        String secretKey = "034zlTH751wqhT5ZzTwTOKCwW0HYo1R3";//用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-chengdu");
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        //指定要上传的文件
        File localFile = convertMultipartFileToFile(file,"D://");
        // 指定文件将要存放的存储桶
        String bucketName = "flycar-yang-1324472389";
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = "folder/picture.jpg";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        return putObjectResult;
    }

    /**
     * 完成就业帮扶,修改状态和时间
     * @param sysStudentHelp
     * @return
     */
    @Override
    public void finishStudentHelp(SysStudentHelp sysStudentHelp) throws Exception {
        //发送企业微信
        String message = "学生姓名："+sysStudentHelp.getStudentName()+"\n"+"问题描述："+sysStudentHelp.getRemark()+"\n"+"完成时间"+sysStudentHelp.getCreatTime()+"\n"+"老师:"+sysStudentHelp.getTeacherName();
        WechatRobotUtil.sendTextMessage(message,new ArrayList());
        //发送邮件,链接的code通过ace加密id,将这个进行拼接
        String encryptedId = LongEncryptionDemo.encryptLong(sysStudentHelp.getId());
        System.out.println(encryptedId);
        //拼接发送邮件，前端根据拼接的code上传到后端进行解密查询到studenthelp表的信息
        String linkText = "我要评价";
        String linkUrl = "http://localhost/evaluate?code=" + encryptedId;
        String messageEmail = "<html><body>" +
                sysStudentHelp.getStudentName() + "你好，对于" +
                sysStudentHelp.getCreatTime() + "的问题是否解决？请点击" +
                "<a href='" + linkUrl + "'>" + linkText + "</a>" +
                "对这次服务做出评价。</body></html>";
        qicqMailTemplate.sendMail(sysStudentHelp.getEmail(),"完成就业帮扶",messageEmail);
        sysStudentHelpMapper.updateSysStudentHelp(sysStudentHelp);
    }

    /**
     * 微信推送消息
     * @param sysStudentHelp
     * @return
     */
    @Override
    public void wechatPush(SysStudentHelp sysStudentHelp) {
        String message = "问题描述:"+sysStudentHelp.getRemark()+"\n"+"预约时间:"+sysStudentHelp.getCreatTime()+"\n"+"具体详细请到学员跟踪系统"+"\n"+"@"+sysStudentHelp.getTeacherName();
        WechatRobotUtil.sendTextMessage(message,new ArrayList());
    }

    /**
     * 通过code获取到学生帮扶信息
     * @param code
     * @return
     */
    @Override
    public SysStudentHelp getCodeByHelp(String code) throws Exception {
        //解密
        Long id = LongEncryptionDemo.decryptLong(code);
        SysStudentHelp sysStudentHelp = selectSysStudentHelpById(id);
        //返回数据
        return sysStudentHelp;
    }

    public static File convertMultipartFileToFile(MultipartFile multipartFile, String tempDirPath) throws IOException {
        // 获取文件原名
        String originalFileName = multipartFile.getOriginalFilename();

        // 创建临时文件路径
        File tempFile = new File(tempDirPath + File.separator + originalFileName);

        // 检查临时目录是否存在，如果不存在则创建
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        // 将MultipartFile的内容写入到临时文件中
        try (InputStream inputStream = multipartFile.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            throw new IOException("Failed to convert MultipartFile to File", e);
        }

        return tempFile;
    }
}
